package com.cn.kehong.service;

import com.cn.kehong.api.IProductPeiJobSupplierService;
import com.cn.kehong.dao.ProductPeiJobSupplierMapper;
import com.cn.kehong.domain.ProductPeiJobSupplier;
import com.cn.kehong.domain.ProductPeiJobSupplierExample;
import com.cn.kehong.utils.CommonUtil;
import com.cn.kehong.utils.Constants;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class ProductPeiJobSupplierServiceImpl implements IProductPeiJobSupplierService {

    @Autowired
    private ProductPeiJobSupplierMapper productPeiJobSupplierMapper;

    @Override
    public List<ProductPeiJobSupplier> getProductPeiJobSupplierByPeiId(String peiId) throws Exception {
        ProductPeiJobSupplierExample example = new ProductPeiJobSupplierExample();
        example.createCriteria().andPeiIdEqualTo(peiId).andStatusEqualTo(Constants.NORMAL_STATUS);
        example.setOrderByClause("create_time asc");
        List<ProductPeiJobSupplier> productPeiJobSuppliers = productPeiJobSupplierMapper.selectByExample(example);
        return productPeiJobSuppliers;
    }

    @Override
    public String addBatchProductPeiJobSuppliers(List<ProductPeiJobSupplier> productPeiJobSuppliers) throws Exception {
        if(CollectionUtils.isEmpty(productPeiJobSuppliers)){
            return "数组为空！";
        }
        String peiId = productPeiJobSuppliers.get(0).getPeiId();
        ProductPeiJobSupplierExample example = new ProductPeiJobSupplierExample();
        example.createCriteria().andPeiIdEqualTo(peiId);
        int count = productPeiJobSupplierMapper.deleteByExample(example);
        if(count < 0){
            return "更新表异常！";
        }
        long nowTime = new Date().getTime();
        for(ProductPeiJobSupplier jobSupplier:productPeiJobSuppliers){
            String id = CommonUtil.generateRandomNum("job_");
            jobSupplier.setId(id);
            jobSupplier.setCreateTime(new Date(nowTime+1000));
        }
        count = productPeiJobSupplierMapper.batchInsertPeiJobSuppliers(productPeiJobSuppliers);
        if(count < 0){
            throw new Exception("数据库插入异常！");
        }
        return "";
    }
}
